package com.hp.easyBuy.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hp.easyBuy.contants.StatusCode;
import com.hp.easyBuy.utils.R;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/*
* 登录验证请求
* 时间：2024年4月1日 16:55:52
* 作者：代奥
* */
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getContextPath();
        //从请求头里面取出token
        String token = request.getHeader("token");
        if(token != null && redisTemplate.getExpire(token) > 0){
            //有token的请求，重置其时间之后正常放行
            redisTemplate.expire(token, 1800, TimeUnit.SECONDS);
            return true;
        }else{
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(R.error(StatusCode.TOKEN_EXPIRED, "token已过期"));
            response.getWriter().write(jsonStr);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
